<style lang="less" scoped>
  .f-ww60 {
    width: 60%;
  }
  .f-ww80 {
    width: 80%;
  }
  .f-ww90 {
    width: 90%;
  }

  .el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }

  .el-col {
    border-radius: 4px;
  }

  .bg-purple-light {
    background: #ffffff;
  }

  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }

  .el-row {
    margin-bottom: 0;
    height: 40px;
  }

  .el-col-8 {
    height: 40px;
  }

  .active {
    display: none;
  }
</style>
<template>
  <section>
    <el-form ref="searchForm" :model="searchForm" label-position="right" class="toolbar" style="height: 90px"
             label-width="120px">
      <el-row style="padding-top: 10px">
        <el-col :span="8">
          <div class="grid-content">
            <el-form-item label="客户名称" prop="memberUserId_EQ">
              <el-select class="f-ww80" v-model="searchForm.memberUserId_EQ"
                         remote
                         :remote-method="searchMemberUsers"
                         filterable
                         placeholder="请选择客户">
                <el-option v-for="(mu,index) in memberUsers" :label="mu.realName"
                           :value="mu.userId" :key="index">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content">
            <el-form-item label="结算方式" prop="receivableType_EQ">
              <el-select class="f-ww80" v-model="searchForm.receivableType_EQ"
                         placeholder="请选择结算方式">
                <el-option v-for="(receivableType,index) in $store.getters.PAY_WAY"
                           :label="receivableType.cnDictValname"
                           :value="receivableType.dictVal" :key="index">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发生日期" prop="happenDate">
            <el-date-picker class="f-ww80"
                            v-model="searchForm.happenDate"
                            type="daterange"
                            placeholder="选择日期范围">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <div class="grid-content">
            <el-form-item label="应收单号" prop="receivableNumber_LIKE">
              <el-input class="f-ww80" v-model="searchForm.receivableNumber_LIKE"
                        placeholder="请输入应收单号"></el-input>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content">
            <el-form-item label="订单编号" prop="orderNumber_LIKE">
              <el-input class="f-ww80" v-model="searchForm.orderNumber_LIKE"
                        placeholder="请输入订单编号"></el-input>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content">
            <el-form-item label="是否已付款" prop="receivableStatus_EQ">
              <el-select class="f-ww80" v-model="searchForm.receivableStatus_EQ"
                         placeholder="请选择已付款状态">
                <el-option v-for="(receivableType,index) in $store.getters.PAY_TYPE"
                           :label="receivableType.cnDictValname"
                           :value="receivableType.dictVal" :key="index">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <div class="f-mt10">
      <el-button type="primary" @click="orderReceivableDialog('add')">新增</el-button>
      <el-button type="primary">打印</el-button>
      <el-button type="primary" class="f-fr" @click="resetSHForm('searchForm')">重置</el-button>
      <el-button type="primary" class="f-fr" @click="searchOrderReceivables">查询</el-button>
    </div>

    <div class="f-mt10">

      <el-table :data="orderReceivableTableData" max-height="650" border>
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column prop="receivableNumber" label="应收单号" width="250">
        </el-table-column>
        <el-table-column prop="happenDate" label="发生日期" width="250">
        </el-table-column>
        <el-table-column prop="receivableTypeModel.cnDictValname" label="结算方式" width="100">
        </el-table-column>
        <el-table-column prop="memberUserName" label="客户名称" width="160">
        </el-table-column>
        <el-table-column prop="orderNumber" label="订单编号" width="240">
        </el-table-column>
        <el-table-column prop="receivableMoney" label="应收总额" width="100">
        </el-table-column>
        <el-table-column prop="receivedMoney" label="已收总额">
        </el-table-column>
        <el-table-column prop="receivedMoney" label="是否付款">
          <template slot-scope="scope">
            <label v-if="scope.row.receivableStatus===102004001">待付款</label>
            <label v-if="scope.row.receivableStatus===102004002">已付款</label>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button type="primary" class="f-mt10 f-mb10"
                       @click="compileOrderReceivable(scope.row,'select')">查看
            </el-button>
            <el-button type="primary">确认收款</el-button>
            <el-button type="primary">收款记录</el-button>
            <el-button type="primary" @click="compileOrderReceivable(scope.row,'compile')"
                       v-if="scope.row.happenType===102006002">编辑
            </el-button>
            <el-button type="danger" class="f-mb10" v-if="scope.row.happenType===102006002"
                       @click="deleteOrderReceivables(scope.row.id)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
                     :current-page="currentPage"
                     :page-size="pageSize"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     layout="total,sizes,prev, pager, next, jumper"
                     :total="total" style="float: right">
      </el-pagination>
    </div>
    <div>
      <el-dialog :title="dialogTitle" :visible.sync="orderReceivableDialogForm" :close-on-click-modal="false">
        <el-form :model="orderReceivableForm" ref="orderReceivableForm" :rules="rules" label-width="80px">
          <el-col :span="8">
            <el-form-item label="应收总额">
              <el-input :disabled="true" v-model="orderReceivableForm.receivableMoney"
                        class="f-ww90"
                        placeholder="应收总额"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结算方式" prop="receivableType">
              <el-select :disabled="selectBo" class="f-ww90"
                         v-model="orderReceivableForm.receivableType"
                         placeholder="请选择结算方式">
                <el-option v-for="(rt,index) in $store.getters.PAY_WAY"
                           :label="rt.cnDictValname"
                           :value="rt.dictVal" :key="index">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="height: 50px">
            <el-form-item label="客户名称" prop="memberUserId">
              <el-select :disabled="selectBo" class="f-ww90"
                         remote
                         :remote-method="searchMemberUsers"
                         filterable
                         @change="searchMemberUsersChange"
                         v-model="orderReceivableForm.memberUserId"
                         placeholder="请选择客户名称">
                <el-option v-for="(memberUser,index) in memberUsers"
                           :label="memberUser.realName"
                           :value-key="memberUser.userId"
                           :value="memberUser.userId" :key="index">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="已收总额">
              <el-input :disabled="true" v-model="orderReceivableForm.receivedMoney"
                        class="f-ww90"
                        placeholder="请输入已收总额"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="应收单号">
              <el-input :disabled="true" v-model="orderReceivableForm.receivableNumber"
                        class="f-ww90"
                        placeholder="请输入应收单号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="height: 50px">
            <el-form-item label="联系电话" prop="phone">
              <el-input type="number" size="11" :disabled="selectBo" v-model="orderReceivableForm.phone" class="f-ww90"
                        placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结余总额">
              <el-input :disabled="true" v-model="orderReceivableForm.verificationMoney"
                        class="f-ww90"
                        placeholder="请输入结余总额"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单编号">
              <el-input :disabled="selectBo" v-model="orderReceivableForm.orderNumber" class="f-ww90"
                        @change="getOrderByOrderNumber" placeholder="请输入订单编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发货日期" prop="happenDate" required>
              <el-date-picker :disabled="selectBo" class="f-ww90" type="date"
                              v-model="orderReceivableForm.happenDate"
                              placeholder="请选择发货日期"
                              :picker-options="happenDateDateValuePOS">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-form>
        <div class="f-mb10">
          <el-button type="text" v-bind:class="{ active: isActive }" @click="orderReceivableDetailDialogChange">
            <i class="el-icon-plus"></i>新增行
          </el-button>
        </div>
        <el-table
          :data="orderReceivableDetailTable"
          border
          style="width: 100%">
          <el-table-column prop="costType" label="费用类型" width="180">
          </el-table-column>
          <el-table-column prop="costName" label="费用名称" width="180">
          </el-table-column>
          <el-table-column prop="receivableMoney" label="费用金额（元）">
          </el-table-column>
          <el-table-column prop="remark" label="备注">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" v-bind:class="{ active: isActive }"
                         @click.native.prevent="deleteRow(scope.$index, orderReceivableDetailTable)">删除行
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button @click="orderReceivableDialogForm = false">取 消</el-button>
          <el-button v-bind:class="{ active: isActive }" type="primary" @click="saveOrderReceivable">确 定
          </el-button>
        </div>
      </el-dialog>
      <el-dialog title="应收单详情" :visible.sync="orderReceivableDetailDialog">
        <el-form ref="orderReceivableDetailForm" :model="orderReceivableDetailForm" label-width="140px"
                 :rules="orderReceivableDetailRules">
          <el-row>
            <el-col :span="12">
              <div class="grid-content">
                <el-form-item label="费用类型" prop="costType">
                  <el-select v-model="orderReceivableDetailForm.costTypeDictId" class="f-ww90"
                             @change="searchCostTypeChange"
                             placeholder="请选择订单状态">
                    <el-option v-for="(costType,index) in $store.getters.ORDER_COST_TYPE"
                               :label="costType.cnDictValname"
                               :value-key="costType.id"
                               :value="costType.id" :key="index">
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content">
                <el-form-item label="费用名称" prop="costName">
                  <el-select v-model="orderReceivableDetailForm.costNameDictId" class="f-ww90"
                             @change="searchCostNameChange" placeholder="请选择订单状态">
                    <el-option
                      v-for="(costName,index) in $store.getters.ORDER_COST_DETAILS"
                      :label="costName.cnDictValname"
                      :value-key="costName.id"
                      :value="costName.id" :key="index">
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div class="grid-content">
                <el-form-item label="费用金额（元）" prop="receivableMoney">
                  <el-input type="number" step="0.01"
                            v-model.number="orderReceivableDetailForm.receivableMoney"
                            class="f-ww90"
                            placeholder="请输入内容"></el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content">
                <el-form-item label="备注">
                  <el-input v-model="orderReceivableDetailForm.remark" class="f-ww90"
                            placeholder="请输入内容"></el-input>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="orderReceivableDetailDialog = false">取 消</el-button>
          <el-button type="primary" @click="addOrderReceivableDetail">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </section>
</template>
<script>
import { getOrderReceivables, saveOrderReceivable, deleteOrderReceivable } from '../../api/order/orderReceivable.js';
import { getOrderTableData } from '../../api/order/order.js';
import { getMemberUsers } from '../../api/customer/maintain.js';
import { isEmpty, toFilters, getSelectObect, resetObjNull } from '../../lib/util.js';

export default {
  data () {
    return {

      memberUserTest: '',
      token: this.$store.state.token,
      dialogTitle: '',
      bo: false,
      selectBo: false,
      isActive: false,
      memberUsers: [],
      happenDateDateValuePOS: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      orderReceivableDetailDialog: false,
      orderReceivableDetailForm: {
        costType: '',
        costTypeDictId: '',
        costTypeModel: '',
        costName: '',
        costNameDictId: '',
        costNameModel: '',
        receivableMoney: '',
        remark: ''
      },
      searchForm: {
        memberUserId_EQ: null,
        receivableType_EQ: null,
        happenDate: null,
        receivableNumber_LIKE: null,
        receivableStatus_EQ: null,
        orderNumber_LIKE: null
      },
      index: 0,
      receivableMoney: '',
      test_t: null,
      test: null,
      orderReceivableDetailTable: [], // 费用明细table
      orderReceivableTableData: [],
      orderReceivableDialogForm: false,
      total: 0,
      sels: [],
      currentPage: 1,
      pageSize: 10,
      sortProp: null,
      sortOrder: 'ascending',
      orderReceivableDetailRules: {
        costType: [
          {required: true, message: '请选择费用类型', trigger: 'blur'}
        ],
        costName: [
          {required: true, message: '请输入费用类型', trigger: 'blur'}
        ],
        receivableMoney: [
          {required: true, type: 'number', message: '请输入费用金额'}
        ]
      },
      rules: {
        receivableType: [
          {required: true, type: 'number', message: '请选择结算方式', trigger: 'blur'}
        ],
        memberUserId: [
          {required: true, message: '请输入客户名称', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入联系电话', trigger: 'blur'},
          {min: 11, max: 11, message: '长度请控制在11位', trigger: 'blur'}
        ],
        happenDate: [
          {type: 'date', required: true, message: '请选择发生时间', trigger: 'blur'}
        ]
      },
      orderReceivableForm: {
        receivableType: '',
        receivableMoney: '',
        memberUserId: '',
        memberUserName: '',
        memberUserModel: {},
        receivedMoney: '',
        receivableNumber: 'YS' + new Date().getTime(),
        phone: '',
        verificationMoney: '',
        orderNumber: '',
        orderReceivableDetail: [],
        deleteOrderReceivableDetail: [],
        happenDate: ''
      },
      deleteOrderReceivableDetail: [],
      dataBk: ''// 时间
    };
  },

  methods: {
    // 多选操作
    selsChange (sels) {
      this.sels = sels;
    },
    // 排序操作
    sortChange (o) {
      this.sortProp = o.prop;
      this.sortOrder = o.order;
      this.searchOrderReceivables();
    },
    // 每页几条操作
    handleSizeChange (val) {
      this.pageSize = val;
      this.searchOrderReceivables();
    },
    // 第几页操作
    handleCurrentChange (val) {
      this.currentPage = val;
      this.searchOrderReceivables();
    },
    orderReceivableDetailDialogChange () {
      this.orderReceivableDetailDialog = true;
      if (this.$refs.orderReceivableDetailForm) {
        this.$refs.orderReceivableDetailForm.resetFields();
      }
      // 当先点击修改，再点击新增，会出现值没有清空,修复处理
      for (let p in this.orderReceivableDetailForm) {
        if (this.orderReceivableDetailForm[p] instanceof Array) {
          this.orderReceivableDetailForm[p] = [];
        } else {
          this.orderReceivableDetailForm[p] = null;
        }
      }
    },
    searchMemberUsersChange (event) {
      this.orderReceivableForm.memberUserId = event;
      this.orderReceivableForm.memberUserName = getSelectObect(event, 'userId', this.memberUsers).realName;
    },

    searchCostTypeChange (val) {
      this.orderReceivableDetailForm.costType = getSelectObect(val, 'id', this.$store.getters.ORDER_COST_TYPE).cnDictValname;
    },
    searchCostNameChange (val) {
      this.orderReceivableDetailForm.costName = getSelectObect(val, 'id', this.$store.getters.ORDER_COST_DETAILS).cnDictValname;
    },
    searchMemberUsers (val) {
      let filters = 'realName?' + val + ';';
      if (!isEmpty(val)) {
        getMemberUsers({
          token: this.token,
          filters: filters + 'status=111002001',
          sorts: '',
          size: '15',
          page: '1'
        }).then((res) => {
          this.memberUsers = res.data.detailModelList;
        });
      }
    },
    /**
       *
       * 新增应收单弹框
       */
    orderReceivableDialog (type) {
      this.orderReceivableDetailTable = [];
      if (type === 'add') {
        this.orderReceivableDialogForm = true;
        this.isActive = false;
        this.selectBo = false;
        this.dialogTitle = '新增应收单';
        this.resetSearchForm();
        this.getMemberUsers();
      }
    },

    /**
       * 编辑应收单
       */
    compileOrderReceivable (row, type) {
      this.memberUserTest = row.memberUserName;

      this.resetSearchForm();
      this.orderReceivableForm = Object.assign({
        receivableMoney: '',
        receivableType: '',
        memberUserId: '',
        memberUserName: '',
        memberUserModel: {},
        receivedMoney: '',
        receivableNumber: '',
        phone: '',
        verificationMoney: '',
        orderNumber: '',
        orderReceivableDetail: [],
        deleteOrderReceivableDetail: [],
        happenDate: ''
      }, row);

      this.isActive = false;
      this.selectBo = false;
      this.orderReceivableDialogForm = true;
      this.dialogTitle = '编辑应收单';
      if (type === 'select') {
        this.dialogTitle = '查看应收单';
        this.selectBo = true;
        this.isActive = true;
      }
      this.orderReceivableDialogForm = true;
      this.orderReceivableDetailTable = row.orderReceivableDetail;
    },

    deleteRow (index, rows) {
      this.deleteOrderReceivableDetail.push(rows[index].id);
      rows.splice(index, 1);
      this.calculatePrice();
    },
    deleteOrderReceivables (id) {
      deleteOrderReceivable(id).then((res) => {
        if (res.data.successFlg) {
          this.$message.success('删除成功');
          this.getOrderReceivables('');
        }
      });
    },
    /**
       * 多条件检索订单信息
       */
    searchOrderReceivables () {
      this.getOrderReceivables(toFilters(this.searchForm));
    },
    getOrderByOrderNumber (val) {
      getOrderTableData({
        token: this.token,
        filters: 'LIKE_orderNumber=' + val,
        sorts: '',
        size: 1,
        page: 1
      }).then((res) => {
        if (res.data.successFlg && res.data.detailModelList.length > 0) {
          let model = res.data.detailModelList[0];
          this.orderReceivableForm.phone = model.mMebPersonal.phone;
          this.orderReceivableForm.memberUserId = model.mMebPersonal.userId;
          this.orderReceivableForm.happenDate = model.createDate;
          this.bo = true;
        }
      });
    },
    addOrderReceivableDetail () {
      this.$refs['orderReceivableDetailForm'].validate((orderCargoFormValid) => {
        if (orderCargoFormValid) {
          let routeFreightNew = Object.assign({}, this.orderReceivableDetailForm);
          this.orderReceivableDetailTable.push(routeFreightNew);
          this.calculatePrice();
        }
      });
    },
    saveOrderReceivable () {
      if (this.orderReceivableDetailTable.length <= 0) {
        return this.$message.error('请填写应收单详情');
      }
      this.orderReceivableForm.deleteOrderReceivableDetail = this.deleteOrderReceivableDetail;
      this.orderReceivableForm.orderReceivableDetail = this.orderReceivableDetailTable;
      this.orderReceivableForm.happenDate = new Date(this.orderReceivableForm.happenDate);
      this.$refs['orderReceivableForm'].validate((orderReceivableValid) => {
        if (orderReceivableValid) {
          this.orderReceivableForm.happenDate = new Date(this.orderReceivableForm.happenDate).Format('yyyy-MM-dd');
          saveOrderReceivable(this.orderReceivableForm).then((res) => {
            if (res.data.successFlg) {
              this.orderReceivableDialogForm = false;
              this.$message.success('应收单生成成功');
              this.getOrderReceivables('');
            } else {
              this.$message.error('应收单生成失败');
            }
          });
        }
      });
    },
    getOrderReceivables (filters) {
      getOrderReceivables({
        filters: filters,
        sorts: '-createDate',
        size: this.pageSize,
        page: this.currentPage
      }).then((res) => {
        if (res.data.successFlg) {
          this.orderReceivableTableData = res.data.detailModelList;
          this.currentPage = res.data.currPage;
          this.total = res.data.totalCount;
          this.pageSize = res.data.pageSize;
        }
      });
    },
    getMemberUsers () {
      getMemberUsers({
        page: 1,
        size: 15,
        filters: 'status=111002001',
        sorts: ''
      }).then((res) => {
        this.memberUsers = res.data.detailModelList;
      });
    },
    resetSearchForm () {
      if (this.$refs.orderReceivableForm) {
        this.$refs.orderReceivableForm.resetFields();
      }
      // 当先点击修改，再点击新增，会出现值没有清空,修复处理
      for (let p in this.orderReceivableForm) {
        if (this.orderReceivableForm[p] instanceof Array) {
          this.orderReceivableForm[p] = [];
        } else {
          this.orderReceivableForm[p] = null;
        }
      }
      this.orderReceivableForm.receivableNumber = 'YS' + new Date().getTime();
    },
    resetSHForm () {
      resetObjNull(this.searchForm);
    },
    /**
       * 计算应收总金额
       */
    calculatePrice () {
      let money = 0;
      for (let ordt in this.orderReceivableDetailTable) {
        if (!isEmpty(this.orderReceivableDetailTable[ordt].receivableMoney)) {
          money = money + this.orderReceivableDetailTable[ordt].receivableMoney;
        }
      }
      this.orderReceivableForm.receivableMoney = Math.round(money * 100) / 100;
    }
  },
  mounted () {
    this.getOrderReceivables('');
    this.getMemberUsers();
    this.$store.commit('initDict');
  }
};
</script>
